// pages/device/sealDetail/sealDetail.js
import lwx from '../../../utils/lwx.js'
import {
  _globle
} from '../../../utils/globle.js'
import devices from '../../../utils/devices.js'

Page({
  _version: '',
  _path: '',
  /**
   * 页面的初始数据
   */
  data: {

    navbar: [{
        name: '待使用记录',
        selected: true,
        color: 'red'
      },
      {
        name: '印章详情',
        selected: false
      }
    ],
    selectIndex: 0,
    devicesList: [],
    detail: {},
    sealid: '',
    isSpecial: false,
    top: '44px',
    devicesInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var isSpecial = options.isSpecial || false;
    var top = '44px';
    if (isSpecial) {
      var top = '0px'
    }
    this.setData({
      sealid: options.sealid,
      isSpecial: isSpecial,
      top: top
    })
    this.loadData();
    this.loadList();
  },
  //获取当前版本路径
  loadVersion: function() {
    if (!this._devices) {
      this._devices = new devices(this.data.detail.devicesCode)
    }
    wx.showLoading({
      title: '读取设备信息',
      mask: true
    })
    this._devices.getDevicesInfo().then(res => {
      console.log(res)
      this.setData({
        devicesInfo: res
      })
      wx.hideLoading()
      // wx.showLoading({
      //   title: '读取状态信息',
      //   mask: true
      // })
      return this._devices.getOperationStatus()
    }).then(res => {
      console.log(res)
      wx.hideLoading()
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: '读取数据失败',
        mask: true,
        icon: 'none'
      })
    })
  },
  checkUpdate: function() {
    lwx.request({
      url: 'devices.update',
      data: {
        devicesId: this.data.detail.devicesId
      }
    }).then(res => {
      console.log(res)
      this._path = res.data.drivePath
      this._version = res.data.version
    }).catch(err => {
      wx.showToast({
        title: '请求失败',
        mask: tru,
        icon: 'none'
      })
    })
  },
  //解锁印章
  lockStateUpdate: function() {
      if (!this._devices) {
        this._devices = new devices(this.data.detail.devicesCode)
      }
      wx.hideLoading()
      wx.showLoading({
        title: '读取状态...',
        mask: true
      })
      this._devices.getOperationStatus().then(res => {
        if (res.operationStatus === 2) {
          wx.hideLoading()
          wx.showLoading({
            title: '解除锁定',
            mask: true
          })
          this._devices.setOperationCommand({
            type: 3,
            sign: this.data.detail.sign,
            rand1: res.rand1,
            rand2: res.rand2
          }).then(res => {
            return new Promise((resolve, reject) => {
              wx.hideLoading()
              wx.showLoading({
                title: '获取结果...',
                mask: true
              })
              // 循环读取状态
              let statusInterval = setInterval(() => {
                this._devices.getOperationStatus().then(res => {
                  // 空闲则是安装完成
                  if (res.operationStatus !== 1) {
                    clearInterval(statusInterval)
                    resolve(res.operationStatus)
                  }
                })
              }, 100)
            })
          }).then(res => {
            wx.hideLoading()
            if (res === 2) {
              wx.showToast({
                title: '解除错误锁定失败',
                mask: true,
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '解除成功',
                mask: true
              })
              // this.nextStep()
            }
          }).catch(err => {
            console.log(err)
            wx.hideLoading()
            wx.showToast({
              title: '解除操作失败',
              mask: true,
              icon: 'none'
            })
          })
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '设备正常，无错误信息',
            mask: true,
            icon: 'none'
          })
        }
      }).catch(res => {
        wx.hideLoading()
        wx.showToast({
          title: '获取运行状态失败',
          mask: true,
          icon: 'none'
        })
      })
  },
  upInstall: function() {
    if (this._devices) {
      console.log('断开连接')
      this._devices.closeConnection()
    }

    // let currentVersion = `${this.data.devicesInfo.majorVersion}.${this.data.devicesInfo.subVersion}.${this.data.devicesInfo.minorVersion}`

    let currentVersion = '0.0.0'
    wx.navigateTo({
      url: `../ota/index/index?deviceCode=${this.data.detail.devicesCode}&currentVersion=${currentVersion}&version=${this._version}&path=${this._path}&deviceId=${this.data.detail.devicesId}&sign=${this.data.detail.sign}`,
    })
  },
  loadList: function() {
    var that = this;
    lwx.request({
      url: "deviceAct.list",
      data: {
        sealId: that.data.sealid
      }
    }).then(res => {
      console.log(res)
      if (res.data.code == '0') {
        that.setData({
          devicesList: res.data.sealDeviceActs
        })
      } else {
        wx.showToast({
          title: res.data.message,
        })
      }
    }).catch(err => {
      console.log('err' + err);
    })
    let devicesList = []
    this.setData({
      devicesList: devicesList,
    })
  },
  loadData: function() {
    var that = this;
    lwx.request({
      url: "devices.info",
      data: {
        sealId: that.data.sealid
      }
    }).then(res => {

      if (res.data.code == '0') {
        const resData = res.data || {}
        const seal = resData.seal || {}
        const sealPrivileges = seal.sealPrivileges || []
        const workflowTypes = seal.workflowTypes || []
        const sealPrivilegesArr = sealPrivileges.map((item) => {
          return item.name
        })
        const workflowTypesArr = workflowTypes.map((item) => {
          return item.workflowTypeStr
        })
        seal.sealPrivilegesStr = sealPrivilegesArr.join("/")
        seal.workflowTypesStr = workflowTypesArr.join("/")
        that.setData({
          detail: seal
        })
        // this.loadVersion();
        this.checkUpdate()
      } else {
        wx.showToast({
          title: res.data.message,
        })
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  select: function(e) {
    var navbar = this.data.navbar;
    for (var i = 0; i < navbar.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        navbar[i].color = 'red';
        navbar[i].borderColor = '#999';
      } else {
        navbar[i].color = '#999';
        navbar[i].borderColor = '#f7f7f7';
      }
    }
    this.setData({
      navbar: navbar,
      selectIndex: e.currentTarget.dataset.index
    })
  },
  //申请重装
  applyRestart: function() {
    wx: wx.navigateTo({
      url: '../applyRestartDevice/applyRestartDevice',
    })
  },
  sealDetail: function(e) {
    // e.currentTarget.dataset.sealid
    console.log(e.currentTarget.dataset.sealid)
    if (e.currentTarget.dataset.sealid) {
      wx.navigateTo({
        url: '../applySealDetail/applySealDetail?devicesActId=' + e.currentTarget.dataset.sealid,
      })
    } else if (e.currentTarget.dataset.devicestakeid) {
      wx.navigateTo({
        url: '../applySealDetail/applySealDetail?devicestakeid=' + e.currentTarget.dataset.devicestakeid,
      })
    }
  },
  disable: function(e) {
    var message = '冻结之后该印章将不能使用，确定冻结？';
    if (e.currentTarget.dataset.disable == 'ENABLE') {
      var message = '解结之后该印章将继续使用，确定解结？';
    }
    wx.showModal({
      title: message,
      confirmText: "确定",
      success: res => {
        if (res.confirm) {
          var that = this;
          lwx.request({
            url: "seal.disable",
            data: {
              sealId: that.data.sealid,
              sealStatus: e.currentTarget.dataset.disable
            }
          }).then(res => {
            console.log(res)
            if (res.data.code == '0') {
              wx.showToast({
                title: res.data.message,
                icon: 'none',
              })
              that.loadData();
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'none',
              })
            }
          }).catch(err => {
            console.log('err' + err);
          })
        } else {

        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    if (this._devices) {
      console.log('断开连接')
      this._devices.closeConnection()
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  
})